local json=require("cocos.cocos2d.json")
local FZutil=require("app.FZutil")
local Language=require("Language")
local FzFileUtils=require("app.public.FzFileUtils")
local FzSound=require("app.public.FzSound")
local Alert=require("app.public.Alert")
local info=require("info")

local function reloadlua()
    print("重新加载更新了的lua文件")
    ReloadLua()
    require("app.FzInit")       --重头加载
    local MyApp=require("app.MyApp"):create()
    cc.exports.MyApp=MyApp
end

local function getSizeStr( size )
    local size_type="bytes"
    local num=size
    if size>1024*1024 then
        num=size/1024/1024
        size_type="MB"
    elseif size>1024 then
        num=size/1024
        size_type="KB"
    end
    return num,size_type
end

local HotUpdaterOld=class("HotUpdaterOld")

function HotUpdaterOld:ctor( UIScene )
	self.UIScene=UIScene
    self.force=false
end

function HotUpdaterOld:initHotUpdateManager()
    if SKIP_HOT_UPDATE then
        return
    end
	local projcet_path=cc.FileUtils:getInstance():fullPathForFilename("project.manifest")
    local downloadPath=FzFileUtils.getDownloadPath()
    local am=fz.FZupdater.create(projcet_path,downloadPath)
    am:retain()
    --local info=require(FzFileUtils.getOriginInfoPath())
    --am:setRemoteManifestUrl(info.manifest_base)   
    local info=json.decode(cc.FileUtils:getInstance():getStringFromFile(projcet_path))
    am:setRemoteManifestUrl(info.packageUrl)
    self.ame_=am
    if not am:getLocalManifest():isLoaded() then
        print("读取本地Manifest文件失败")
        Alert:show(Language.updater.title_fail,Language.updater.no_loacl_Manifest)
    else
        self:loadOldManifest()
        local listener = fz.EventListenerAssetsManagerEx.create(am,function(event) self:onUpdateEvent(event) end)
        self.listener=listener
        cc.Director:getInstance():getEventDispatcher():addEventListenerWithFixedPriority(listener, -1)
    end
end

local DECOMPRESSING=11

function HotUpdaterOld:onUpdateEvent(event)
    print("onUpdateEvent",event:getEventCode())
    local am=self.ame_
    local eventCode = event:getEventCode()
    if eventCode == cc.EventAssetsManagerEx.EventCode.ERROR_NO_LOCAL_MANIFEST then
        Alert:show(Language.updater.title_fail,Language.updater.no_loacl_Manifest)
    elseif  eventCode == cc.EventAssetsManagerEx.EventCode.UPDATE_PROGRESSION then
        local assetId = event:getAssetId()
        local percent = event:getPercent()
        local percentFile=event:getPercentByFile()
        local totalByte=event:getTotal()
        local nowByte=event:getNow()
        local strInfo = ""

        if assetId == cc.AssetsManagerExStatic.VERSION_ID then
            strInfo = string.format("Version file: %d%%", percent)
        elseif assetId == cc.AssetsManagerExStatic.MANIFEST_ID then
            strInfo = string.format("Manifest file: %d%%", percent)
            self.download_version=true
            if not self.force then 
                self:showAsk()
            end
        else
            local num_now,size_type_now=getSizeStr(nowByte)
            local num_total,size_type_total=getSizeStr(totalByte)
            strInfo = string.format("%d%%,size:%.2f%s/%.2f%s", percent,num_now,size_type_now,num_total,size_type_total)
            local updateNode=self.UIScene:getUpdateNode()
            updateNode.LoadingBar:setPercent(percent)
            updateNode.Text_process:setString(strInfo)
            -- print(percentFile,percent)
        end
        -- print("progress:"..strInfo)
    elseif eventCode == cc.EventAssetsManagerEx.EventCode.ERROR_DOWNLOAD_MANIFEST or
        eventCode == cc.EventAssetsManagerEx.EventCode.ERROR_PARSE_MANIFEST then
        Alert:show(Language.updater.title_fail,Language.updater.remote_Manifest_fail,Alert.TYPE_OK,function()
            self.ame_:FZdownloadManifest()
        end)
    elseif eventCode == cc.EventAssetsManagerEx.EventCode.ALREADY_UP_TO_DATE then
        reloadlua()
        self.UIScene:EnterGame()	        
    elseif eventCode == cc.EventAssetsManagerEx.EventCode.UPDATE_FINISHED then
        print("更新下载完成")
        if cc.exports.fix_restart_lua then 
            fix_restart_lua()
        else
            reloadlua()
            MyApp:enterScene("MainScene")	
        end        
    elseif eventCode == cc.EventAssetsManagerEx.EventCode.ERROR_UPDATING then
        print("更新错误")
        local err_msg_str=string.format("%s,%s,c version:<%d>",event:getAssetId(),event:getMessage(),info.cpp_version)
        Alert:show(Language.updater.title_fail,err_msg_str)
        FZutil.send_log(err_msg_str,1)
        self:showUpdateBtn(true)
    elseif eventCode == cc.EventAssetsManagerEx.EventCode.NEW_VERSION_FOUND then
        print("有新版本")
        if not self.load_manifest then
            self.load_manifest=true     --防止重复调用
            am:FZdownloadManifest()
        end
    elseif eventCode == cc.EventAssetsManagerEx.EventCode.ASSET_UPDATED then
        print("下载成功",event:getAssetId())
    elseif eventCode == cc.EventAssetsManagerEx.EventCode.UPDATE_FAILED then
        print("下载失败")
        Alert:show(Language.updater.title_fail,event:getAssetId()..Language.updater.msg_download_err,Alert.TYPE_OK)
        self:showUpdateBtn(true)
    elseif eventCode == cc.EventAssetsManagerEx.EventCode.ERROR_DECOMPRESS then
        Alert:show(Language.updater.title_fail,event:getAssetId()..Language.updater.msg_unzip_err)
        self:showUpdateBtn(true)
    elseif eventCode == DECOMPRESSING then 
        local assetId = event:getAssetId()  --filename
        local message = event:getMessage()  --file progress
        local updateNode=self.UIScene:getUpdateNode()
        updateNode.LoadingBar:setPercent(100)
        local str=Language.updater.decompressing
        if message~="" then 
            local arr=string.split(message, "/")
            print(arr[1],arr[2])
            local current=tonumber(arr[1])
            local total=tonumber(arr[2])
            str=str .. ":" .. message
            local percent=current/total*100
            updateNode.LoadingBar:setPercent(percent)
        end
        updateNode.Text_process:setString(str)
    end
end

function HotUpdaterOld:showAsk()
	if not self.new_mainfest then
        local lbuf=cc.FileUtils:getInstance():getStringFromFile("project.manifest.temp")
        self.new_mainfest=json.decode(lbuf)
        if not self.new_mainfest then   --文件下载失败
            Alert:show(Language.updater.title_check_fail,Language.updater.msg_download_info_fail,Alert.TYPE_YES_NO,function(isY)
                if isY then     --重新下载project.manifest
                    self.ame_:FZdownloadManifest()
                else
                    MyApp:enterScene("MainScene")
                end
            end)
            return  --跳出方法
        end
    end
    local new_mainfest=self.new_mainfest
    local old_mainfest=self.old_manifest
    local old_assets=old_mainfest.assets
    local need_bytes=0
    for name, pkg in pairs(new_mainfest.assets) do
        if old_assets[name] and old_assets[name].md5 == pkg.md5 then
            --do nothing 跳过
        else 
            need_bytes=need_bytes+pkg.bytes
        end
    end
    if need_bytes==0 then 
        reloadlua()
        self.UIScene:EnterGame()
    else 
        local num,size_type=getSizeStr(need_bytes)
        local msg=string.format(Language.need_update,num,size_type)
        Alert:show(Language.updater.title_need_update,msg,Alert.TYPE_YES_NO,function(yes)
            self.UIScene:getUpdateNode()
            if yes then
                self:showUpdateBtn(false)
                self:doUpdate()
            else
                self:showUpdateBtn(true)
            end
        end)
    end
end

function HotUpdaterOld:checkUpdate()
    if self.download_version then
        self:showAsk()
    else
        self.ame_:checkUpdate()
    end
end

function HotUpdaterOld:onCleanup()
	if self.ame_ then
        self.ame_:release()
        self.ame_=nil
    end
    if self.listener then
        cc.Director:getInstance():getEventDispatcher():removeEventListener(self.listener)
        self.listener=nil
    end
end

function HotUpdaterOld:loadOldManifest()
    local lbuf=cc.FileUtils:getInstance():getStringFromFile("project.manifest")
    local lmf=json.decode(lbuf)
    self.old_manifest=lmf
    self.current_version=lmf.version
end

function HotUpdaterOld:doUpdate(force)
    print("do update")
    self.ame_:update()
    self.force=force or false
end

function HotUpdaterOld:showUpdateBtn(isShow)
    local updatenode=self.UIScene:getUpdateNode()
    if isShow then 
        if updatenode.Button_Clean then 
            updatenode.Button_Clean:show()
        end
        updatenode.Button_update:show()
    else
        updatenode.Button_update:hide()
        if updatenode.Button_Clean then 
            updatenode.Button_Clean:hide()
        end
    end
end

return HotUpdaterOld